package com.hunliji.monitor.web.strategy.alert.handlers;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.hunliji.monitor.manager.api.FeiShuManager;
import com.hunliji.monitor.manager.api.model.param.FeiShuSendMsgManagerParam;
import com.hunliji.monitor.service.api.AlertChatBindService;
import com.hunliji.monitor.service.api.ChatGroupService;
import com.hunliji.monitor.service.api.InformActionStrategyService;
import com.hunliji.monitor.service.api.UserInfoService;
import com.hunliji.monitor.service.api.model.bo.*;
import com.hunliji.monitor.service.api.model.param.AlertNotifyParam;
import com.hunliji.monitor.service.api.model.param.QueryInformActionStrategyParam;
import com.hunliji.monitor.share.component.convertor.ConverterFacade;
import com.hunliji.monitor.share.enums.AlertActionTypeEnum;
import com.hunliji.monitor.share.enums.AtTypeEnum;
import com.hunliji.monitor.share.enums.ReceiveIdTypeEnum;
import com.hunliji.monitor.web.facade.FeiShuFacade;
import com.hunliji.monitor.web.model.param.AliyunAlertNotifyParam;
import com.hunliji.monitor.web.strategy.alert.AbstractAlertAction;
import com.hunliji.monitor.web.strategy.alert.model.AlertActionResultBO;
import com.hunliji.monitor.web.strategy.alert.model.AlertContext;
import com.hunliji.monitor.web.strategy.alert.util.TemplateUtil;

import java.util.*;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

/**
 * File：FeishuChatAlertActionHandler.java<br> Title: <br> Description: <br>
 *
 * @author lejin Date: 2022/10/11
 */
@Slf4j
@Component
public class FeishuChatAlertActionHandler extends AbstractAlertAction {

    @Resource
    ChatGroupService chatGroupService;

    @Resource
    AlertChatBindService alertChatBindService;

    @Resource
    UserInfoService userInfoService;

    @Resource
    FeiShuManager feiShuManager;

    @Resource
    FeiShuFacade feiShuFacade;

    @Resource
    ConverterFacade converterFacade;
    @Resource
    private InformActionStrategyService informActionStrategyService;

    @Override
    protected AlertActionTypeEnum getAlertActionType() {
        return AlertActionTypeEnum.FEISHU_CHAT;
    }

    @Override
    protected Boolean validate(AlertContext context) {
        return Boolean.TRUE;
    }

    @Override
    protected void doProcess(AlertContext context, AlertActionResultBO result) throws Exception {
        Long alertConfigId = context.getAlertConfigId();
        AliyunAlertNotifyParam aliyunAlertNotifyParam = context.getAliyunAlertNotifyParam();
        List<AlertChatBindBO> alertChatBindBOS = alertChatBindService.listByQuery(alertConfigId,
            null);
        if(CollectionUtils.isEmpty(alertChatBindBOS)){
            result.setSuccess(Boolean.FALSE);
            result.setErrorMsg("绑定群聊id为空");
            return;
        }
        List<Long> chatGroupIds = alertChatBindBOS.stream().map(AlertChatBindBO::getChatGroupId)
            .collect(Collectors.toList());
        Map<Long, ChatGroupBO> chatGroupBOMap = chatGroupService.getMapByIds(chatGroupIds);
        String accessToken = feiShuFacade.getAccessToken();
        if(StringUtils.isEmpty(accessToken)){
            result.setSuccess(Boolean.FALSE);
            result.setErrorMsg("获取飞书token失败");
            return;
        }
        alertChatBindBOS.forEach(alertChatBindBO -> {
            Long chatGroupId = alertChatBindBO.getChatGroupId();
            ChatGroupBO chatGroupBO = chatGroupBOMap.get(chatGroupId);
            if(Objects.isNull(chatGroupBO) || StringUtils.isEmpty(chatGroupBO.getFeiShuChatId())){
                result.setSuccess(Boolean.FALSE);
                result.setErrorMsg("群聊id为空");
                return;
            }
            String feiShuChatId = chatGroupBO.getFeiShuChatId();
            sendChatMessage(alertChatBindBO, aliyunAlertNotifyParam, feiShuChatId, accessToken);
        });
    }

    private void sendChatMessage(AlertChatBindBO alertChatBindBO, AliyunAlertNotifyParam aliyunAlertNotifyParam, String feiShuChatId, String accessToken){
        String atType = alertChatBindBO.getAtType();
        String msgTemplate = alertChatBindBO.getMsgTemplate();
        String atUserInfoIds = alertChatBindBO.getAtUserInfoIds();
        List<UserInfoBO> atUsers = Lists.newArrayList();
        if(StringUtils.isEmpty(msgTemplate)){
            FeiShuSendMsgManagerParam param = FeiShuSendMsgManagerParam.builder()
                .receiveIdType(ReceiveIdTypeEnum.CHAT_ID.getCode())
                .receiveId(feiShuChatId)
                .msgType(alertChatBindBO.getMsgType()).build();
            if(AtTypeEnum.NONE.getCode().equals(atType)){
                param.setContent(JSON.toJSONString(FeishuPostMessageBO.getDefaultFeishuPostMessage(converterFacade.convert(aliyunAlertNotifyParam,
                    AlertNotifyParam.class), atUsers)));
                feiShuManager.sendMsg(param, accessToken);
            } else if(AtTypeEnum.USER.getCode().equals(atType)){
                if(!StringUtils.isEmpty(atUserInfoIds)){
                    String[] userInfoIds = atUserInfoIds.split("\\|");
                    List<Long> userInfoId = Lists.newArrayList();
                    try {
                        userInfoId.addAll(Arrays.stream(userInfoIds).map(Long::valueOf)
                            .collect(Collectors.toList()));
                    } catch (Exception e){
                        log.warn("userInfoIds格式化失败", e);
                    }
                    atUsers = userInfoService.getListByIds(userInfoId);
                }
                param.setContent(JSON.toJSONString(FeishuPostMessageBO.getDefaultFeishuPostMessage(converterFacade.convert(aliyunAlertNotifyParam,
                    AlertNotifyParam.class), atUsers)));
                feiShuManager.sendMsg(param, accessToken);
            } else if(AtTypeEnum.ALL.getCode().equals(atType)){
                atUsers.add(UserInfoBO.getAtAllUserInfo());
                param.setContent(JSON.toJSONString(FeishuPostMessageBO.getDefaultFeishuPostMessage(converterFacade.convert(aliyunAlertNotifyParam,
                    AlertNotifyParam.class), atUsers)));
                feiShuManager.sendMsg(param, accessToken);
            }else if(AtTypeEnum.ACTION_STRATEGY.getCode().equals(atType)){
                log.info("执行通知行动策略");
                List<Long> userIdList = new ArrayList<>();
                //如果需要走行动策略，则取行动策略数据
                QueryInformActionStrategyParam queryInformActionStrategyParam = QueryInformActionStrategyParam.build(alertChatBindBO.getId(),aliyunAlertNotifyParam.getCurrentKey(),null);
                List<InformActionStrategyBO> informActionStrategyBOList = informActionStrategyService.query(queryInformActionStrategyParam);
                if(!CollectionUtils.isEmpty(informActionStrategyBOList)){
                    userIdList = informActionStrategyBOList.stream().map(InformActionStrategyBO::getUserId).collect(Collectors.toList());
                }
                atUsers = userInfoService.getListByIds(userIdList);
                param.setContent(JSON.toJSONString(FeishuPostMessageBO.getActionStrategyFeishuPostMessage(converterFacade.convert(aliyunAlertNotifyParam,
                        AlertNotifyParam.class), atUsers)));
                feiShuManager.sendMsg(param, accessToken);
            }
        } else {
            String content = TemplateUtil.getConstantByTemplate(msgTemplate,
                aliyunAlertNotifyParam);
            FeiShuSendMsgManagerParam param = FeiShuSendMsgManagerParam.builder()
                .receiveIdType(ReceiveIdTypeEnum.CHAT_ID.getCode())
                .receiveId(feiShuChatId)
                .msgType(alertChatBindBO.getMsgType())
                .content(content)
                .build();
            feiShuManager.sendMsg(param, accessToken);
        }

    }
}
